using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Waf.Applications;
using System.Windows.Threading;
using TrackMe.Apps;
using TrackMe.Apps.VM;


[Export]
public class ApplicationController : Controller
{
	#pragma warning disable 0649
	[Import] 
	private WidgetVM widgetVM;
	[Import]
	private CreateVM createVM;
    [Import] 
    private TaskSearchVM searchVM;
    [Import] 
    private RecentTaskVM recentVM;
	[Import]
	private IDatabase database;
	[Import]
	private IDialogService dialogs;
	#pragma warning restore 0649

	readonly DispatcherTimer timer;

    [ImportingConstructor]
    private ApplicationController(CompositionContainer container)
	{
		timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Background, OnTimer, Dispatcher.CurrentDispatcher);
		timer.Start();
	}

	private void OnTimer(object sender, EventArgs e)
	{
		widgetVM.HeartBeat();
		int jobId = widgetVM.CurrentJob != null ? widgetVM.CurrentJob.Id: 0;
		database.Heartbeat(jobId);
		//CheckInactivityPeriod();
	}


	public void Run()
	{
		widgetVM.AddChild(createVM);
        widgetVM.AddChild(searchVM);
        widgetVM.AddChild(recentVM);
        widgetVM.Show();
		CheckOrphanJob();
	}

	private void CheckOrphanJob()
	{
		var orphanJob = database.JobInProgress();
		if (orphanJob != null)
		{
			if (dialogs.ShowYesNoQuestion("Continue last job?"))
			{
				widgetVM.ContinueOrphanJob(database.ResumeOrpahJob(orphanJob.Id));
			}else
			{
				database.CancelOrphanJob(orphanJob.Id);
			}
		}
	}
}
